<template>
  <div>
    <Form ref="form" :rules="formValidate" :label-width="90" :model="form">
          <FormItem label="姓名" prop="name">
            <Input v-model="form.name" />
          </FormItem>
          <FormItem label="毕业院校" prop="college">
            <Input v-model="form.college" />
          </FormItem>
          <FormItem label="专业分类" prop="specialtyTypeId">
            <Select v-model="form.specialtyTypeId">
                <Option v-for="(specialtyType) in specialtyTypeData"
                        :key="specialtyType.id"
                        :value="specialtyType.specialtyTypeCode"
                >{{specialtyType.specialtyTypeName}}</Option>
            </Select>
          </FormItem>
          <FormItem label="导师类型" prop="teacherTypeId">
            <Select v-model="form.teacherTypeId">
                <Option v-for="(teacherType) in teacherTypeData"
                        :key="teacherType.id"
                        :value="teacherType.teacherTypeCode"
                >{{teacherType.teacherTypeName}}</Option>
            </Select>
          </FormItem>
          <FormItem label="地区" prop="districtId">
            <Select v-model="form.districtId">
                <Option v-for="(district) in districtData"
                        :key="district.id"
                        :value="district.districtCode"
                >{{district.districtName}}</Option>
            </Select>
          </FormItem>
          <FormItem label="简介" prop="intro">
            <Input v-model="form.intro" type="textarea" :rows="8" />
          </FormItem>
          <FormItem v-privilege="'file-filePage-upload'">
            <Upload
              :action="uploadUrl"
              :headers="uploadHeader"
              :onError="uploadError"
              :onSuccess="uploadSuccess"
              :showUploadList="true"
            >
              <Button icon="ios-cloud-upload-outline" type="primary">上传图片</Button>
            </Upload>
        </FormItem>
    </Form>
    <Row class="code-row-bg" justify="end" type="flex">
      <Button @click="cancel" style="margin-right:10px">取消</Button>
      <Button @click="save" type="primary">保存</Button>
    </Row>
  </div>
</template>
<script>
  import { teacherApi } from '@/api/teacher';
  import { fileApi } from '@/api/file';
  import {specialtyTypeApi} from '@/api/specialty-type';
  import {teacherTypeApi} from '@/api/teacher-type';
  import {districtApi} from '@/api/district';
  import Cookies from 'js-cookie';
  import { TOKEN_KEY } from '@/lib/cookie';
  export default {
    name: 'TeacherListForm',
    components: {
    },
    props: {
      //是否为更新表单
      isUpdate: {
        type: Boolean,
        default: true
      },
      //更新的表单数据对象
      updateData: {
        type: Object
      }
    },
    data() {
      return {
        //表单数据
        form: {
         name:null,
         college:null,
         intro:null,
         pictureId:null,
         specialtyTypeId:null,
         teacherTypeId:null,
         districtId:null
        },
        //表单验证
        formValidate: {
        //课程名
        name:[{ required: true, message: '请输入姓名', trigger: 'blur' }],
        //毕业院校
        college:[{ required: true, message: '请输入毕业院校', trigger: 'blur' }],
        //简介
        intro:[{ required: true, message: '请输入简介', trigger: 'blur' }]
        },
        // 专业分类数据
        specialtyTypeData:null,
        // 教师分类数据
        teacherTypeData:null,
        // 地区数据
        districtData:null
      };
    },
  watch: {
      updateData: function(newValue, oldValue) {
          this.$refs['form'].resetFields();
          if (this.isUpdate) {
              for (let k in this.form) {
                  this.$set(this.form, k, newValue[k]);
              }
              this.$set(this.form, 'id', newValue['id']);
          }
      },
      isUpdate: function(newValue, oldValue) {
          if (!newValue) {
              this.resetForm();
              this.$refs['form'].resetFields();
          }
      }
  },
  computed: {
    uploadHeader: function() {
      let header = {
        'x-access-token': Cookies.get(TOKEN_KEY)
      };
      return header;
    },
    uploadUrl: function() {
      let baseUrl = fileApi.fileUploadLocalUrl;
      let url = baseUrl + 1;
      return url;
    }
  },
    created() {},
    mounted() {
      this.querySpecialtyType();
      this.queryTeacherType();
      this.queryDistrict();
    },
    methods: {
      // 上传成功钩子
      async uploadSuccess(e) {
        if (!e.success) {
          console.error(e);
          return this.uploadError();
        }
        this.$Spin.show();
        let reqBody = {
          moduleId: 1,
          moduleType: 1,
          fileLocationType: 1,
          fileName: e.data.fileName,
          filePath: e.data.filePath
        };
        let rep = await fileApi.addFile(reqBody);
        this.form.pictureId = rep.data;
        this.$Spin.hide();
        this.$Message.success('上传成功');
        // this.find();
      },
      // 上传失败钩子
      uploadError(e) {
        this.$Message.error('上传出错，请重试！');
        console.error(e);
        this.find();
      },
      cancel() {
        this.$emit('on-form-close');
      },
      save() {
       this.$refs['form'].validate(valid => {
         if (valid) {
           if (this.isUpdate) {
            this.update();
           } else {
             this.add();
           }
         } else {
          this.$Message.error('参数验证错误，请仔细填写表单数据!');
         }
       });
      },
    resetForm() {
        this.form = {
            name:null,
            college:null,
            intro:null,
            pictureId:null,
            specialtyTypeId:null,
            teacherTypeId:null,
            districtId:null
        };
        this.$refs['form'].resetFields();
      },
      async add() {
        this.$Spin.show();
        // let res = await peonyApi.addPeony(this.form);
        let res = await teacherApi.addTeacher(this.form);
        this.$Message.success(res.msg);
        this.$Spin.hide();
        this.resetForm();
        this.$emit('on-form-close');
      },
      async update() {
        this.$Spin.show();
        // let res = await peonyApi.updatePeony(this.form);
        this.$Message.success(res.msg);
        this.$Spin.hide();
        this.resetForm();
        this.$emit('on-form-close');
      },
      async querySpecialtyType() {
        let result = await specialtyTypeApi.queryAll();
        this.specialtyTypeData = result.data;
      },
      async queryTeacherType() {
          let result = await teacherTypeApi.queryAll();
          this.teacherTypeData = result.data;
      },
      async queryDistrict() {
          let result = await districtApi.queryAll();
          this.districtData = result.data;
      }
    }
  };
</script>